package com.qf.agro.interceptors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qf.agro.common.Constant;
import com.qf.agro.common.ResultInfo;
import com.qf.agro.common.SysUserHolder;
import com.qf.agro.pojo.SysUser;
import com.qf.agro.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 判断校验用户是否登录过
 * @author 千锋健哥
 */
@Component
public class CheckLoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 判断方法的请求类型, 如果是options请求, 无条件放行
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        //2. 获取请求头中的jwt令牌
        String authorization = request.getHeader("Authorization");

        //3. 判断如果jwt为空, 返回错误信息
        if (StringUtils.isEmpty(authorization)) {
            ResultInfo resultInfo = ResultInfo.error(Constant.NOT_LOGIN);
            //把错误信息对象转成json
            String jsonStr = JSON.toJSONString(request);
            //通过响应流, 写回到前端
            response.getWriter().write(jsonStr);
            return false;
        }

        //4. 解析jwt
        try {
            Claims claims = JwtUtil.parseJWT(authorization);
            //5. 如果解析成功, 将用户信息放入ThreadLocal中保存, 方便后台获取当前登录用户信息
            //jwt的唯一id
            String jti = claims.getId();
            //jwt中的内容
            String subject = claims.getSubject();
            //借助json工具类进行转换对象
            JSONObject json = JSON.parseObject(subject);
            SysUser sysUser = JSON.toJavaObject(json, SysUser.class);
            if (sysUser != null) {
                SysUserHolder.set(sysUser);
            }
            return true;

        } catch (Exception e) {
            //6. 如果解析报错, 说明jwt要么被篡改, 要么超时, 返回错误信息
            e.printStackTrace();
            ResultInfo resultInfo = ResultInfo.error(Constant.NOT_LOGIN);
            //把错误信息对象转成json
            String jsonStr = JSON.toJSONString(request);
            //通过响应流, 写回到前端
            response.getWriter().write(jsonStr);
            return false;
        }

    }

}
